﻿#region Copyright Notice
// This file is part of GestionPedago.
// <description>
// Copyright (C) 2012 ENI Ecole Informatique
// 
// GestionPedago is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// <program> is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace GestionPedago.EntityContext.EntityOPTools
{
    /// <summary>
    /// Classe utilitaire sur les expressions EntityFramework
    /// </summary>
    public class EntityExpressionTools
    {
        /// <summary>
        /// Méthode de construction d'une expression where ... in ...
        /// </summary>
        /// <typeparam name="TElement">Le type de l'Entity sur lequel porte l'expression</typeparam>
        /// <typeparam name="TValue">Le type des valeurs</typeparam>
        /// <param name="valueSelector">Le prédicat de sélection</param>
        /// <param name="values">La liste des valeurs</param>
        /// <returns>L'expression where ... in ...</returns>
        public static Expression<Func<TElement, bool>> BuildWhereInExpression<TElement, TValue>(Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
        {
            if (null == valueSelector) { throw new ArgumentNullException("valueSelector"); }
            if (null == values) { throw new ArgumentNullException("values"); }
            ParameterExpression p = valueSelector.Parameters.Single();
            // p => valueSelector(p) == values[0] || valueSelector(p) == ...
            if (!values.Any())
            {
                return e => false;
            }
            var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));
            var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));
            return Expression.Lambda<Func<TElement, bool>>(body, p);
        }
    }
}
